//
//  MusicViewController.m
//  LO_MUSIC
//
//  Created by 向祖华 on 16/2/24.
//  Copyright © 2016年 杨少锋. All rights reserved.
//

#import "MusicViewController.h"
#import "RequestURL.h"
#import "DownloadImageOperation.h"
#import "MusicPlayer.h"

@interface MusicViewController ()<UITableViewDataSource,UITableViewDelegate,DownloadImageOperationDelegate>

@property(nonatomic,strong)UITableView * rootTableView;
//模型数组
@property(nonatomic,strong)NSArray * modelArray;
//队列
@property(nonatomic,strong)NSOperationQueue * queue;
//存放图片url的字典
@property(nonatomic,strong)NSMutableDictionary * imageDic;

//存放正在下载的图片的字典
@property(nonatomic,strong)NSMutableDictionary * operationDic;
//创建一个播放器
@property(nonatomic,strong)MusicPlayer*musicPlayer;


@end

@implementation MusicViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    //初始化tableView
    self.rootTableView = [[UITableView alloc] initWithFrame:self.view.bounds style:(UITableViewStylePlain)];
    
    //设置tableView的代理
    self.rootTableView.delegate = self;
    self.rootTableView.dataSource = self;
    
    [self.view addSubview:self.rootTableView];
    
    //请求数据
    //创建weakself用于block内替换self
    __weak typeof (self) weakSelf = self;
    
    RequestURL * request = [[RequestURL alloc] init];
    //调用请求数据的方法
    [request requestMusiclistWithSuccess:^(id item) {
        
        weakSelf.modelArray = item;
        //UI重新加载数据
        [weakSelf.rootTableView reloadData];
        
    } faile:^(NSError * err) {
        
        NSLog(@"%@",err);
    }];
    
    //初始化播放器
    self.musicPlayer = [[MusicPlayer alloc] init];
    
}

#pragma mark - tableView的代理方实现（delegate/datasource）
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.modelArray.count;
}

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    //只要注册过就要加forIndexPath
    
    //重用池
    UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"cell_music"];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:(UITableViewCellStyleSubtitle) reuseIdentifier:@"cell_music"];
    }
#pragma mark - cell的赋值

    MusicMode * model = self.modelArray[indexPath.row];
    cell.textLabel.text = model.name;//歌名
    cell.detailTextLabel.text = model.singer;//歌手名
    //细胞的颜色随机
    CGFloat num1 = arc4random() % 255 ;
    CGFloat num2 = arc4random() %255;
    CGFloat num3 = arc4random() % 255;
    cell.backgroundColor = [UIColor colorWithRed:num1/255.0 green:num2/255.0 blue:num3/255.0 alpha:1];
    //先去存储已下载图片的字典中查找
    if ([self.imageDic.allKeys containsObject:model.picUrl])//字典中存在图片
    {
        //从字典中取出图片给imageView赋值
        cell.imageView.image = self.imageDic[model.picUrl];//字典中图片网址为键，对应图片为值
    }
    else//字典中不存在该图片
    {
        //使用占位图
        cell.imageView.image = [UIImage imageNamed:@"1"];
        //判断UI界面是否在滑动，滑动就不加载，静止才加载
        if (self.rootTableView.dragging || self.rootTableView.decelerating)//如果正在滑动，不处理图片
        {
            return cell;//直接返回
        }
        
        //判断当前细胞的数据是不是正在下载，如果正在下载，不用管它；如果不是正在下载（而又没有下载），则创建下载操作，并放到队列
        if ([self.operationDic.allKeys containsObject:model.picUrl])//如果存放正在下载图片网址的字典中有对应的图片网址，说明正在下载
        {}
        else//不是正在下载的图片
        {
            //创建一个下载图片的操作
            DownloadImageOperation * downloadImage = [[DownloadImageOperation alloc] init];
            //
            downloadImage.url = model.picUrl;//取图片的网址
            downloadImage.indexPath = indexPath;//取细胞位置
            
            downloadImage.delegate = self;//设置代理
            //将下载操作添加到队列
            [self.queue addOperation:downloadImage];
            
            //添加到存放正在下载图片的字典
            [self.operationDic setValue:downloadImage forKey:downloadImage.url];
        }
    }
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 80;
}

//结束滑动
-(void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    if (!decelerate)//yes是减速过程中
    {
        //滑动结束后加载
        [self loadImage];
    }
}

//结束减速
-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    [self loadImage];
}

-(void)loadImage
{
   //取出当前可用的cell
    NSArray * visiblePaths = [self.rootTableView indexPathsForVisibleRows];
    //重新加载cell
    [self.rootTableView reloadRowsAtIndexPaths:visiblePaths withRowAnimation:(UITableViewRowAnimationNone)];
    
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
//    MusicPlayer*music = [[MusicPlayer alloc] init];
    
    [self.musicPlayer sendIndex:^(NSInteger index) {
        self.CurrentPlayingSongNumeber = index;
    }];
    if (indexPath.row == self.CurrentPlayingSongNumeber ) {
        [self.navigationController pushViewController:self.musicPlayer animated:YES];
    }
    else
    {
    //获取当前所点击的细胞
    UITableViewCell * cell = [tableView cellForRowAtIndexPath:indexPath];
    //获取当前的细胞对应的模型值
    [self.musicPlayer setValue:self.modelArray[indexPath.row] forKey:@"model"];
    //获取当前细胞的图片
    [self.musicPlayer setValue:cell.imageView.image forKey:@"image"];
    
    //将存储数据的数组传到播放控制器界面
    [self.musicPlayer setValue:self.modelArray forKey:@"allDataArray"];
    //将所点击的细胞的位置传到播放器控制界面
    [self.musicPlayer setValue:indexPath forKey:@"indexPath"];
        
    [self.navigationController pushViewController:self.musicPlayer animated:YES];
    }
    
}




#pragma mark - 实现图片加到cell上的代理方法
//downImagedelegate，代理方法
-(void)getImage:(UIImage *)image operation:(DownloadImageOperation *)operation
{
    UITableViewCell * cell = [self.rootTableView cellForRowAtIndexPath:operation.indexPath];
    cell.imageView.image = image;
    //图片下载下来之后放在字典中
    [self.imageDic setValue:image forKey:operation.url];
    //从正在下载的字典中移除操作
    [self.operationDic removeObjectForKey:operation.url];
    
}

#pragma mark — 懒加载
//队列的懒加载
-(NSOperationQueue*)queue{
    if (!_queue) {
        _queue = [[NSOperationQueue alloc]init];
        _queue.maxConcurrentOperationCount = 3;//最大并发数（最多同时只下载3个）
    }
    return _queue;
}

//存放已下载图片字典的懒加载
-(NSMutableDictionary*)imageDic
{
    if (!_imageDic) {
        _imageDic  = [[NSMutableDictionary alloc]init];
        
    }
    return _imageDic;
}


//存放正在下载图片字典的懒加载
-(NSMutableDictionary *)operationDic
{
    if (!_operationDic) {
        _operationDic = [[NSMutableDictionary alloc]init];
    }
    return _operationDic;
}












- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
